package com.phpxiu.app.okhttp;

import android.content.Context;

import com.google.gson.Gson;
import com.phpxiu.app.download.PicDownloadCallBack;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.okhttp.cookies.OKHttpCookieManager;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.utils.KKYUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @file
 * @brief OKHttp请求类
 * @author 吴金洲
 * @note  OKHttp请求类
 * 1.初始化OKhttp，如cookies初始化等
 * 2.post请求
 * 3.get请求
 * 4.取消某个请求
 * 5.取消所有请求
 * 6.初始化所有已知业务请求错误码
 *
 */
public class OKHttp {
    public final static Gson GSON=new Gson();

    public final static MediaType JSON= MediaType.parse("application/json; charset=utf-8");

    private static final MediaType IMG= MediaType.parse("image/png");

    public final static Map<String,String>RESPONSE_ERR=new HashMap<String,String>();

    private static OkHttpClient HTTP;

    public static void init(Context context){
        HTTP= new OkHttpClient.Builder()
                .cookieJar(new OKHttpCookieManager(context))//设置cookies自动管理器
                .connectTimeout(5,TimeUnit.SECONDS)
                .readTimeout(5,TimeUnit.SECONDS)
                //.proxy(new Proxy(Proxy.Type.HTTP,new InetSocketAddress("192.168.199.209",8888)))//设置代理，抓包
                .build();
        parseErrMsg(context);
    }

    /**
     * 请求数据
     * @param url 接口
     * @param param 参数
     * @param TAG 标志
     * @param uiCallback 异步回调
     */
    public static void post(String url, String param, String TAG, OKHttpUIHandler uiCallback){
        KKYUtil.log(TAG+"请求接口："+url+"  参数："+param);
        if(HTTP!=null){
            HTTP.newCall(
                    new Request.Builder()
                            .url(url)
                            .post(RequestBody.create(JSON, param))
                            .tag(TAG)
                            .build()).enqueue(uiCallback);
        }
    }

    /**
     * 请求数据
     * @param url 接口
     * @param TAG 标志
     * @param uiCallback 异步回调
     */
    public static void get(String url, String TAG, OKHttpUIHandler uiCallback){
        if(HTTP!=null){
            HTTP.newCall(
                    new Request.Builder()
                            .url(url)
                            .tag(TAG)
                            .build()).enqueue(uiCallback);
        }
    }

    /**
     * 请求数据
     * @param url 接口
     * @param TAG 标志
     * @param callback 异步回调
     */
    public static void get(String url, String TAG, OKHttpCallback callback){
        if(HTTP!=null){
            HTTP.newCall(
                    new Request.Builder()
                            .url(url)
                            .tag(TAG)
                            .build()).enqueue(callback);
        }
    }
    /**
     * 参数不变，如心跳类的请求
     * @param request
     * @param uiCallback
     */
    public static void post(Request request, OKHttpUIHandler uiCallback){
        if(HTTP!=null) {
            try {
                Call call = HTTP.newCall(request);
                call.enqueue(uiCallback);
                call.execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载图片
     * @param url 图片url
     * @param callBack
     */
    public static void downloadPic(String url, PicDownloadCallBack callBack){
        if(HTTP!=null){
            HTTP.newCall(
                    new Request.Builder()
                            .url(url)
                            .tag(callBack.getId())
                            .build()).enqueue(callBack);
        }
    }

    /**
     *
     * @param api 服务器接口
     * @param filed 表单字段名
     * @param imageFile 上传文件
     * @param tag 请求标识
     * @param callback 请求成功或失败回调
     */
    public static void upload(String api,String filed,File imageFile,String tag,OKHttpCallback callback){
        try {
            MultipartBody.Builder form = new MultipartBody.Builder().setType(MultipartBody.FORM);
            form.addFormDataPart(filed,imageFile.getName(),RequestBody.create(IMG,imageFile));
            MultipartBody formBody = form.build();
            if(HTTP!=null){
                HTTP.newCall(
                        new Request.Builder()
                                .url(api)
                                .post(formBody)
                                .tag(tag)
                                .build()).enqueue(callback);
            }
        }catch (Exception e){
            if(callback!=null){
                callback.onErr(e.getMessage());
            }
        }
    }

    /**
     * 取消所有请求
     */
    public static void cancelRequest(){
        HTTP.dispatcher().cancelAll();
    }

    /**
     * 取消某个请求
     * @param TAG
     */
    public static void cancelRequest(String TAG){
        List<Call> calls=new ArrayList<Call>();
        calls.addAll(HTTP.dispatcher().queuedCalls());
        calls.addAll(HTTP.dispatcher().runningCalls());
        for (Call c:calls){
            if(TAG.equals(c.request().tag())){
                try {
                    c.cancel();
                }catch (Exception e){

                }
            }
        }
    }

    /**
     * 初始化响应异常信息
     * @param context
     */
    public static void parseErrMsg(Context context){
        RESPONSE_ERR.put("90000",context.getString(R.string.code_90000));
        RESPONSE_ERR.put("90001",context.getString(R.string.code_90001));

        RESPONSE_ERR.put("10001",context.getString(R.string.code_10001));
        RESPONSE_ERR.put("10002",context.getString(R.string.code_10002));
        RESPONSE_ERR.put("10003",context.getString(R.string.code_10003));
        RESPONSE_ERR.put("10004",context.getString(R.string.code_10004));
        RESPONSE_ERR.put("10005",context.getString(R.string.code_10005));
        RESPONSE_ERR.put("10006",context.getString(R.string.code_10006));
        RESPONSE_ERR.put("10007",context.getString(R.string.code_10007));

        RESPONSE_ERR.put("11001",context.getString(R.string.code_11001));
        RESPONSE_ERR.put("11002",context.getString(R.string.code_11002));

        RESPONSE_ERR.put("20001",context.getString(R.string.code_20001));
        RESPONSE_ERR.put("20002",context.getString(R.string.code_20002));
        RESPONSE_ERR.put("20003",context.getString(R.string.code_20003));
        RESPONSE_ERR.put("20004",context.getString(R.string.code_20004));
        RESPONSE_ERR.put("20005",context.getString(R.string.code_20005));

        RESPONSE_ERR.put("21001",context.getString(R.string.code_21001));
        RESPONSE_ERR.put("21002",context.getString(R.string.code_21002));

        RESPONSE_ERR.put("10008",context.getString(R.string.code_10008));
        RESPONSE_ERR.put("10009",context.getString(R.string.code_10009));
        RESPONSE_ERR.put("10010",context.getString(R.string.code_10010));
        RESPONSE_ERR.put("10011",context.getString(R.string.code_10011));
        RESPONSE_ERR.put("10012",context.getString(R.string.code_10012));

        RESPONSE_ERR.put("21003",context.getString(R.string.code_21003));
        RESPONSE_ERR.put("21004",context.getString(R.string.code_21004));
    }
}
